import { createRouter, createWebHistory } from "vue-router";
import LoginPage from "../views/LoginPage.vue";
import MainPage from "../views/MainPage.vue";
import BorrowPage from '../views/BorrowPage.vue';
import ReturnPage from '../views/ReturnPage.vue';
import SearchPage from '../views/SearchPage.vue';
import BorrowHistoryPage from '../views/BorrowHistoryPage.vue';
import ManageUser from "../views/ManageUser.vue";
import ManageBook from "../views/ManageBook.vue";

const routes = [
    { path: "/", name: "Login", component: LoginPage, meta: { requiresAuth: false } },
    { path: "/main", name: "Main", component: MainPage, meta: { requiresAuth: true } },
    { path: '/borrow', name: 'Borrow', component: BorrowPage, meta: { requiresAuth: true } },
    { path: '/return', name: 'Return', component: ReturnPage, meta: { requiresAuth: true } },
    { path: '/search', name: 'Search', component: SearchPage, meta: { requiresAuth: true } },
    { path: '/borrow-history', name: 'BorrowHistory', component: BorrowHistoryPage, meta: { requiresAuth: true } },
    { path: "/manage-user", name: "ManageUser", component: ManageUser, meta: { requiresAuth: true, onlyAdmin: true } },
    { path: "/manage-book", name: "ManageBook", component: ManageBook, meta: { requiresAuth: true, onlyAdmin: true } },
];

const router = createRouter({
    history: createWebHistory(),
    routes,
});

router.beforeEach((to, from, next) => {
    const role = localStorage.getItem("role");

    if (to.meta.requiresAuth && !role) {
        next('/');
    } else if (to.name === "Login" && role) {
        next('/main');
    } else if (to.meta.requiresAuth && to.meta.onlyAdmin && role !== 'admin') {
        next('/main');
    } else {
        next();
    }
});

export default router;
